import axios from "axios";
import { message } from "../common/util";
const CancelToken = axios.CancelToken;
// 默认初始化 建议修改
axios.interceptors.request.use(
  (suc) => {
    return suc;
  },
  (err) => {
    return err;
  }
);
axios.interceptors.response.use(
  (suc) => {
    console.log(suc);
    message.success("成功");
    localStorage.setItem("token", suc.headers.token);
    return suc.data;
  },
  (err) => {
    switch (err.response.status) {
      case 400:
        message.error("错误请求");
        break;
      case 401:
        message.error("未授权，请重新登录");
        break;
      case 403:
        message.error("拒绝访问");
        break;
      case 404:
        message.error("请求错误，未找到该资源");
        break;
      case 408:
        message.error("请求超时");
        break;
      case 500:
        message.error("服务器端出错");
        break;
      case 501:
        message.error("网络未实现");
        break;
      case 502:
        message.error("网络错误");
        break;
      case 503:
        message.error("服务不可用");
        break;
      case 504:
        message.error("网络超时");
        break;
      case 505:
        message.error("http版本不支持该请求");
        break;
      default:
        message.error(`连接错误${err.response.status}`);
    }

    return err;
  }
);
const header = {
  Authorization: "123",
};
const objCallback = function(method, url, data) {
  console.log(method);
  const obj = {
    url: url,
    data: data,
    timeout: 5000,
    params: {
      ...data,
    },
    method: method,
    headers: {
      ...header,
    },
    cancelToken: new CancelToken(function(res) {
      console.log(res);
      // res('121') 执行就会 取消发送请求
    }),
  };
  if (method === "post") {
    delete obj.params;
  }
  if (method === "get") {
    delete obj.data;
  }
  return axios(obj);
};
const httpAxios = function(method, url, data) {
  const http = objCallback(method, url, data);
  return http;
};
export default httpAxios;
